<template>
  <!-- 期初库存维护表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="700"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品编号">
            <el-input v-model="formData.materialCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称">
            <el-input v-model="formData.materialName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年月" prop="yearMonthInventory">
            <el-input v-model="formData.yearMonthInventory" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity">
            <el-input
              v-model="formData.quantity"
              placeholder="请输入数量"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单重" prop="singleWeight">
            <el-input
              v-model="formData.singleWeight"
              placeholder="请输入单重"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="吨位" prop="tonnage">
            <el-input
              v-model="formData.tonnage"
              placeholder="请输入吨位"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上月废品率" prop="lastMonthScrapRate">
            <el-input
              v-model="formData.lastMonthScrapRate"
              placeholder="请输入上月废品率"
              clearable
            />
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input v-if="!props.isReadonly" v-model="formData.remarks" placeholder="请输入备注" clearable/>

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>-->
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { validateNumber } from "@/utils/commonHooks"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESINITIALINVENTORYMAINTENANCEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  materialCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  yearMonthInventory: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  quantity: [
    { required: true, message: "请输入数量", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        validateNumber(rule, value, callback);
      },
      trigger: "blur",
    },
  ],
  singleWeight: [
    { required: true, message: "请输入单重", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        validateNumber(rule, value, callback);
      },
      trigger: "blur",
    },
  ],
  tonnage: [
    { required: true, message: "请输入吨位", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        validateNumber(rule, value, callback);
      },
      trigger: "blur",
    },
  ],
  lastMonthScrapRate: [
    { required: true, message: "上月废品率", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        validateNumber(rule, value, callback);
      },
      trigger: "blur",
    },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  yearMonthInventory: "",
  inventoryYear: "",
  inventoryMonth: "",
  quantity: "",
  singleWeight: "",
  tonnage: "",
  lastMonthScrapRate: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        materialId,
        materialCode,
        materialName,
        yearMonthInventory,
        inventoryYear,
        inventoryMonth,
        quantity,
        singleWeight,
        tonnage,
        lastMonthScrapRate,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        materialId,
        materialCode,
        materialName,
        yearMonthInventory,
        inventoryYear,
        inventoryMonth,
        quantity,
        singleWeight,
        tonnage,
        lastMonthScrapRate,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.yearMonthInventory = "";
  formData.inventoryYear = "";
  formData.inventoryMonth = "";
  formData.quantity = "";
  formData.singleWeight = "";
  formData.tonnage = "";
  formData.lastMonthScrapRate = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 期初库存维护表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesinitialinventorymaintenance/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
